/**
 * @Author YuanYuan
 * @Date 2022/7/24
 * @Time 18:09
 */
public class HashBuck2<K,V> {

    public HashBuck2(Node<K, V>[] array, int usedSize) {
        this.array = array;
        this.usedSize = usedSize;
    }

    static class Node<K,V> {
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int usedSize;//记录 当前哈希桶当中 有效数据的个数
    public static final float DEFAULT_LOAD_FACTOR = 0.75F;

    public void put (K key,V val) {
        int ret = key.hashCode()%array.length;
        Node<K,V> cur= array[ret];
        while (null!=cur) {
            if(cur.key.equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key, val);
        node.next = array[ret];
        array[ret] = node.next;
        if(loadFactor()>DEFAULT_LOAD_FACTOR) {
            grow();
        }
        this.usedSize++;
    }
    private float loadFactor() {
        return (this.usedSize*1.0f)/array.length;
    }
    private void grow() {
        Node<K,V>[] newarray = (Node<K,V>[])new Node[array.length*2];
        int  len = newarray.length;
        for (int i = 0; i < array.length; i++) {
            if(null != array[i]) {
                Node<K,V> cur = array[i];
                while(null != cur) {
                    int ret = cur.key.hashCode()%len;
                    Node<K,V> curnext = cur.next;
                    cur.next = newarray[ret];
                    newarray[ret] = cur;
                    cur = curnext;
                }
            }
        }
        this.array = newarray;
    }
    public V get(K key) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if(cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
